<template>
  <el-input
    v-model="numValue"
    ref="refInput"
    v-bind="$attrs"
    oninput="value=value.replace(/[^0-9\-\+]/g,'')"
    @blur="blurHandler"
    @input="inputHandler"
  >
    <!--传递插槽-->
    <template v-for="(item, key, index) in $slots" :key="index" v-slot:[key]>
      <slot :name="key"></slot>
    </template>
  </el-input>
</template>
<script lang="ts" setup>
import { ref, watch, computed, onMounted } from 'vue'
import { UPDATE_MODEL_EVENT } from '@/utils/constants'
type TargetElement = HTMLInputElement | HTMLTextAreaElement
const props = defineProps({
  modelValue: [String, Number]
});
const emit = defineEmits([UPDATE_MODEL_EVENT]);
const refInput = ref();
const numValue = ref();

const setInputValue = () => {
  numValue.value = inputValue.value
}

const inputValue = computed(() =>
  props.modelValue === null || props.modelValue === undefined
    ? ''
    : String(props.modelValue)
)

watch(inputValue, () => setInputValue())

onMounted(() => {
  setInputValue();
});

const inputHandler = (val:string)=>{
  emit(UPDATE_MODEL_EVENT, val);
}

const blurHandler = (event:FocusEvent) => {
  const { value } = event.target as TargetElement
  let val = value;
  let val2 = /^-?\d+$/.test(val) ? val : '';
  if (val != val2) {
    numValue.value = val2;
    emit(UPDATE_MODEL_EVENT, val2);
  }
}
</script>
